package com.xoa.controller.workflow;

import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.workflow.FlowRunLogMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunLog;
import com.xoa.model.workflow.FlowTypeModel;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.syspara.SysParaService;
import com.xoa.service.workflow.flowtype.FlowTypeService;
import com.xoa.service.workflow.wrapper.JobSelectorWrapper;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.dataSource.ContextHolder;
import org.apache.http.entity.ContentType;
import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 创建作者:   张勇
 * 创建日期:   2017/5/8 16:51
 * 类介绍  :
 * 构造参数:
 */
@Controller
@RequestMapping("/flow")
public class FlowTypeController {
    @Resource
    private EnclosureService enclosureService;
    @Resource
    private FlowTypeService flowTypeService;

    @Resource
    SysParaService sysParaService;
    @Resource
    DocumentSerivce documentSerivce;
    @Resource
    AttachmentMapper attachmentMapper;
    @Resource
    DocumentModelMapper documentModelMapper;
    @Autowired
    private FlowRunLogMapper flowRunLogMapper;
    @Resource
    private FlowRunMapper flowRunMapper;
    @Autowired
    private WFELog wfeLog;
    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/8 16:55
     * 方法介绍:   新建流程
     * 参数说明:   获取页面传递对象参数
     *
     * @return
     */
    @RequestMapping(value = "newFlow", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    void saveFlow(FlowTypeModel flowTypeModel, HttpServletRequest request,HttpServletResponse response) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        ToJson<FlowTypeModel> flowTypeModelToJson = flowTypeService.saveFlow(flowTypeModel);
        response.setContentType("text/html; charset=utf-8");
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(servletOutputStream,"UTF-8");
            ow.write(JSONObject.toJSONString(flowTypeModelToJson));
            ow.flush();
            ow.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/23 17:47
     * 方法介绍:   自定义属性所有查询，根据flowId
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "selectAllFlow", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson<FlowTypeModel> selectAllFlow(@RequestParam("flowId") Integer flowId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return flowTypeService.selectAllFlow(flowId, request);
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/23 19:41
     * 方法介绍:   自定义属性根据flowId修改
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "updateFlow", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public @ResponseBody
    void updateFlow(FlowTypeModel flowTypeModel, HttpServletRequest request,HttpServletResponse response) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        response.setContentType("text/html; charset=utf-8");
        ToJson<FlowTypeModel> flowTypeModelToJson = flowTypeService.updateFlow(flowTypeModel);
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(servletOutputStream,"UTF-8");
            ow.write(JSONObject.toJSONString(flowTypeModelToJson));
            ow.flush();
            ow.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "selectAttachment", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson selectAttachmentAndInstructions(HttpServletRequest request,
                                           @RequestParam("flowId") Integer flowId,
                                           @RequestParam("formId") Integer formId) {
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        ContextHolder.setConsumerType(sqlType);
        return flowTypeService.selectAttachmentAndInstructions(flowId, formId, sqlType);
    }

    @RequestMapping("/flowNews")
    public String flow(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/flowtype/flowNews";
    }
    @RequestMapping("/fileHref")
    @ResponseBody
    public String fileHref(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/formtype/fileHref";
    }

    @RequestMapping("/flieCheck")
    @ResponseBody
    public String flieCheck(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/formtype/flieCheck";
    }
    //流程设计中查询配置页面
    @RequestMapping("/queryConfiguration")
    public String queryConfiguration(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/flowsettting/theDesignProcess/queryConfiguration";
    }
    @RequestMapping("/flowNew")
    public String newflow(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/flowtype/flownew";
    }

    @RequestMapping("/flowlistbysort")
    @ResponseBody
    public ToJson<FlowTypeModel> flowListBySort(Integer flowId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return flowTypeService.quertBySortId(flowId,request);
    }

    @RequestMapping("/flowBySearch")
    @ResponseBody
    public ToJson<FlowTypeModel> flowBySearch(String searchValue, Integer flowId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return flowTypeService.flowBySearch(searchValue, flowId);
    }

    @RequestMapping("/flowAuthOrSearch")
    @ResponseBody
    public ToJson<FlowTypeModel> selectFlowAuthOrSearch(HttpServletRequest request, String searchValue, Integer sortId) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return flowTypeService.selectFlowAuthOrSearch(request, searchValue, sortId);
    }

    /**
     * 2018/12/17 常用工作
     * 王禹萌
     * @param request
     * @return
     */
    @RequestMapping("/flowAuthOrSearchCommonWork")
    @ResponseBody
    public ToJson<FlowTypeModel> flowAuthOrSearchCommonWork(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return flowTypeService.flowAuthOrSearchCommonWork(request);
    }

    @RequestMapping("/type/index")
    public String flowTypeIndex(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        if (!sysParaService.checkIsHaveSecure(user,7)){
            return "app/common/development";
        }
        return "app/workflow/flowtype/index";
    }
//    @RequestMapping("/type/flowdesigner")
//    public String flowdesigner(HttpServletRequest request, Model model, Integer formId){
//        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute(
//                "loginDateSouse"));
//        model.addAttribute("formId",formId);
//        return "app/workflow/flowtype/flowdesigner";
//    }

    @RequestMapping("/flowDetailInfo")
    @ResponseBody
    public ToJson flowDetailInfo(Integer flowId) {
        return flowTypeService.selectFlowDetailInfo(flowId);
    }

    @RequestMapping(value = "/fileUpload")
    @ResponseBody
    public void uploadFile(@RequestParam("file") MultipartFile[] files, String module,
                                   @RequestParam(value = "company", required = false) String company,
                                   HttpServletRequest request,HttpServletResponse response) {
        BaseWrappers wrappers = new BaseWrappers();
        StringBuffer sb = new StringBuffer();
        if (StringUtils.checkNull(company)) {
            if(request.getSession().getAttribute("loginDateSouse")!=null&&!"null".equals((String) request.getSession().getAttribute("loginDateSouse"))){
                sb.append("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
            }else{
                sb.append("xoa1001");
            }
        } else {
            sb.append(company);
        }
        try {
            List<Attachment> list = enclosureService.upload(files, sb.toString(), module);
            for (Attachment attachment : list) {
                int aid = attachment.getAid();
                String attachId = attachment.getAttachId();
                String ym = attachment.getYm();
                String attachName = attachment.getAttachName();
                String all = aid + "@" + ym + "_" + attachId;
                attachment.setAttStrId(all);
                attachment.setAttStrName(attachName);
            }
            wrappers.setDatas(list);
            wrappers.setFlag(true);
            wrappers.setStatus(true);
        } catch (Exception e) {
            e.printStackTrace();
            wrappers.setFlag(false);
            wrappers.setStatus(false);
            wrappers.setMsg("error");
        }
        response.setContentType("text/html; charset=utf-8");
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(servletOutputStream,"UTF-8");
            ow.write(JSONObject.toJSONString(wrappers));
            ow.flush();
            ow.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Created by:   韩东堂
     * date:   2017/8/9 14:08
     * description:   表单（根据表单id）
     *
     * @param flowId 表单Id
     * @return
     */
    @RequestMapping("/checkOut")
    @ResponseBody
    public void checkOut(HttpServletRequest request, HttpServletResponse response, Integer flowId) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        OutputStream os = null;
        try {
            BaseWrapper wrapper = flowTypeService.getFlowOutModel(flowId);
            Document doc = (Document) wrapper.getData();
            XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
            String fileName = "新建导出流程.xml";
            if (!StringUtils.checkNull(wrapper.getMsg())) {
                fileName = wrapper.getMsg() + ".xml";
            }

            String userAgent = request.getHeader("User-Agent").toUpperCase();
            if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") ||userAgent.contains("QTWEBENGINE")) {
                // win10 ie edge 浏览器 和其他系统的ie
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (userAgent.contains("MOZILLA")) {//google,火狐浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }else {
                // fe
                fileName = new String(fileName.getBytes("iso-8859-1"), "UTF-8");
            }

            response.setHeader("content-disposition", "attachment;filename=" + fileName);

            os = response.getOutputStream();
            xmlOutputter.output(doc, os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            if (os != null) {
                try {
                    os.close();
                } catch (Exception p) {
                    p.printStackTrace();
                }
            }
        }
    }


    @RequestMapping("/inputFlow")
    @ResponseBody
    public BaseWrapper inputFlow(Integer flowId, @RequestParam(name = "file") MultipartFile file) {
        return flowTypeService.intputFlowFile(flowId, file);
    }

    @RequestMapping("/deleteFlow")
    @ResponseBody
    public BaseWrapper deleteFlow(Integer flowId) {
        return flowTypeService.deleteFlow(flowId);
    }

    @RequestMapping("/clearFlow")
    @ResponseBody
    public BaseWrapper clearFlow(Integer flowId) {
        return flowTypeService.clearFlow(flowId);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2018/1/26 10:47
     * 方法介绍:   查询所有设计流程
     * 参数说明:
     * @return
     */
    @RequestMapping("/selAllType")
    @ResponseBody
    public ToJson<FlowTypeModel> selAllType() {
        return flowTypeService.selAllType();
    }

    /**
     * 添加表单查询下拉框一二级名称查询
     * 作者:王禹萌
     * 时间：2018-07-05 10：25
     *  @param request
     * @return
     */
    @RequestMapping("/selOneToAllType")
    @ResponseBody
    public JobSelectorWrapper selOneToAllType(HttpServletRequest request){
        return flowTypeService.selOneToAllType(request);
    }
    /**
     *
     * @作者
     * @创建日期
     * @方法介绍 流程一级分类下的设计流程
     * @参数说明 @return
     * @return
     */
    @RequestMapping("/getFristFlowType")
    @ResponseBody
    public AjaxJson selByFlowSort(Integer sortId, HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("user", user.getUserId() == null ? "" : user.getUserId());
        param.put("deptId", user.getDeptId() == null ? "" : user.getDeptId());
        param.put("privId", user.getUserPriv() == null ? "" : user.getUserPriv());
        param.put("sortId", sortId);
        return flowTypeService.selFlowSorByAndroid(param);
    }


    /**
     * 工作查询的高级查询流程获取
     * 作者:
     * 时间：2018-07-05 10：25
     *  @param request
     * @return
     */
    @RequestMapping("/searchAllType")
    @ResponseBody
    public JobSelectorWrapper searchAllType(HttpServletRequest request){
        return flowTypeService.searchAllType(request);
    }


    /**
     * 工作流新建流程表单下拉框
     * 作者:
     * 时间：2018-07-05 10：25
     *  @param request
     * @return
     */
    @RequestMapping("/selectFrom")
    @ResponseBody
    public JobSelectorWrapper selectFrom(HttpServletRequest request){
        return flowTypeService.selectFrom(request);
    }

    /**
     * 克隆流程
     *  @param request
     * @return
     */
    @RequestMapping("/flowClone")
    @ResponseBody
    public ToJson flowClone(HttpServletRequest request){
        return flowTypeService.flowClone(request);
    }
    /**
     * 获取当前流程的说明文档附件信息
     *  @param request
     * @return
     */
    @RequestMapping("/getAttachment")
    @ResponseBody
    public ToJson getAttachment(HttpServletRequest request){
        return flowTypeService.getAttachment(request);
    }

    //按照年份查询数据（流程门户显示）
    @RequestMapping("/findFlowDataByYear")
    @ResponseBody
    public ToJson<FlowTypeModel> flowData(HttpServletRequest request,Integer flag){
        return flowTypeService.flowData(request,flag);
    }

    //查询流程设计中的查询配置
    @RequestMapping("/flowTypequeryList")
    @ResponseBody
    public ToJson<FlowTypeModel> flowTypequeryList(Integer flowId){
        return flowTypeService.flowTypequeryList(flowId);
    }
    //设置流程设计中的查询配置
    @RequestMapping("/updateQueryList")
    @ResponseBody
    public ToJson updateQueryList(FlowTypeModel flowTypeModel){
        return flowTypeService.updateQueryList(flowTypeModel);
    }

    //公文正文上传文件并复制文件
    @RequestMapping(value = "/docUploadFile")
    @ResponseBody
    public void docUploadFile(@RequestParam("file") MultipartFile[] files, String module,
                              @RequestParam(value = "company", required = false) String company,
                              HttpServletRequest request, HttpServletResponse response) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        BaseWrappers wrappers = new BaseWrappers();
        String id = request.getParameter("id");//公文主键id
        String flowPrcs = request.getParameter("flowPrcs");
        String prcsId = request.getParameter("prcsId");
        String fileType = request.getParameter("fileType");//判断正文类型 1-编辑正文，复制到存档一份   2-修订正文   3-word转pdf文件
        DocumentModelWithBLOBs documentModelWithBLOBs = new DocumentModelWithBLOBs();
        documentModelWithBLOBs.setId(Integer.parseInt(id));
        FileUploadUtil fileUploadUtil = new FileUploadUtil();
        StringBuffer sb = new StringBuffer();
        if (StringUtils.checkNull(company)) {
            if (request.getSession().getAttribute("loginDateSouse") != null && !"null".equals((String) request.getSession().getAttribute("loginDateSouse"))) {
                sb.append("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
            } else {
                sb.append("xoa1001");
            }
        } else {
            sb.append(company);
        }
        try {
            //公文实体对象
            DocumentModelWithBLOBs doc = documentModelMapper.selectByPrimaryKey(Integer.parseInt(id));
            //获取流程实体对象
            FlowRun flowRun = flowRunMapper.find(doc.getRunId());
            //获取后缀名
            String s = files[0].getOriginalFilename().substring(files[0].getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            //1、word转pdf文件需要给文件重命名    --- 命名规则统一取流程名称
            if ((s.equals("pdf")&&fileType.equals("3"))||((fileType.equals("1")))) {
                InputStream inputStream = files[0].getInputStream();
                try {
                    String newName =null;
                    if(fileType.equals("1")){//兼容webOffice上传文件将文件重命名
                        newName=flowRun.getRunName()+"."+s;
                    }else{//
                        newName=flowRun.getRunName() + ".pdf";
                    }
                    MultipartFile multipartFile = new MockMultipartFile("File", newName, "text/plain", inputStream);
                    files[0] = multipartFile;
                    inputStream.close();
                } catch (Exception e) {
                    inputStream.close();
                    e.printStackTrace();
                }
            }
            //上传到服务器
            List<Attachment> list = enclosureService.upload(files, sb.toString(), module);
            for (Attachment attachment : list) {
                FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
                int aid = attachment.getAid();
                String attachId = attachment.getAttachId();
                String ym = attachment.getYm();
                String attachName = attachment.getAttachName();
                String all = aid + "@" + ym + "_" + attachId;
                attachment.setAttStrId(all);
                attachment.setAttStrName(attachName);
                if ((s.equals("doc") || s.equals("docx"))&&fileType.equals("1")) {
                    //编辑正文
                    documentModelWithBLOBs.setMainFile(attachment.getAttStrId());
                    documentModelWithBLOBs.setMainFileName(attachment.getAttStrName());
                    //复制到存档一份
                    List<Attachment> sonAttach = fileUploadUtil.copyFiles(list, sb.toString(), "document", "document");
                    for (Attachment att : sonAttach) {
                        enclosureService.saveAttachment(att);
                    }
                    Object[] o = FileUploadUtil.reAttachment(sonAttach);
                    //存档正文
                    documentModelWithBLOBs.setMainOriginFile(o[0].toString().split(",")[0]);
                    documentModelWithBLOBs.setMainOriginFileName(o[1].toString().split("\\*")[0]);
                    //将版式正文，修订正文对应字段清空
                    documentSerivce.clearMainpdf(Integer.parseInt(id));
                    flowRunLog.setType(Constant.TYPE23);
                } else if (s.equals("pdf")) {
                    //版式正文
                    documentModelWithBLOBs.setMainAipFile(attachment.getAttStrId());
                    documentModelWithBLOBs.setMainAipFileName(attachment.getAttStrName());
                    flowRunLog.setType(Constant.TYPE24);
                } else if((s.equals("doc") || s.equals("docx"))&&fileType.equals("2")) {
                    //修订正文
                    documentModelWithBLOBs.setMainClearFile(list.get(0).getAttStrId());
                    documentModelWithBLOBs.setMainClearFileName(list.get(0).getAttStrName());
                    flowRunLog.setType(Constant.TYPE23);
                }
                /**** 正文上传文件添加日志****/
                flowRunLog.setRunId(flowRun.getRunId());
                flowRunLog.setRunName(flowRun.getRunName());
                flowRunLog.setFlowId(flowRun.getFlowId());
                flowRunLog.setUserId(user.getUserId());
                flowRunLog.setContent("["+user.getUserName()+"]在流水号："+flowRun.getRunId()+",标题为："+flowRun.getRunName()+",上传名称为："+attachName+"的正文");
                flowRunLog.setTime(new Date());
                flowRunLog.setPrcsId(StringUtils.checkNull(prcsId)?null:Integer.parseInt(prcsId));
                flowRunLog.setFlowPrcs(StringUtils.checkNull(flowPrcs)?null:Integer.parseInt(flowPrcs));
                flowRunLogMapper.insertSelective(flowRunLog);
            }
            int i = documentSerivce.updateDocument(documentModelWithBLOBs);
            if (i == 1) {
                wrappers.setDatas(list);
                wrappers.setFlag(true);
                wrappers.setStatus(true);
                wrappers.setMsg("ok");
            } else {
                wrappers.setFlag(false);
                wrappers.setStatus(false);
                wrappers.setMsg("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            wrappers.setFlag(false);
            wrappers.setStatus(false);
            wrappers.setMsg("异常");
        }
        response.setContentType("text/html; charset=utf-8");
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(servletOutputStream, "UTF-8");
            ow.write(JSONObject.toJSONString(wrappers));
            ow.flush();
            ow.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 流程门户是否可以新建流程权限判断
     * @param request
     * @param flowId 要新建的流程id
     * @return
     */
    @RequestMapping("/checkWFNewPriv")
    @ResponseBody
    public AjaxJson checkWFNewPriv(HttpServletRequest request, Integer flowId) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return flowTypeService.checkWFNewPriv(user, flowId);
    }


}
